﻿using System.Windows.Controls;
using Microsoft.Office.Interop.Excel;
using ViewModels;
using ObjectModel.Excel;
using AppEvents = ObjectModel.Excel.AppEvents;

namespace ViewComponents
{
    /// <summary>
    /// Interaction logic for GetRangeControl.xaml
    /// </summary>
    public partial class GetRangeControl : UserControl
    {
        private System.Windows.Forms.Form mParentForm;
        
        public GetRangeControl()
        {
            InitializeComponent();
            AddToForm();

            DataContext = AppEvents.SelectedRange;
        }

        public LinkedRangesViewModel ViewModel { get; set; }

        private void AddToForm()
        {
            System.Windows.Forms.Integration.ElementHost host = new System.Windows.Forms.Integration.ElementHost();
            host.Dock = System.Windows.Forms.DockStyle.Fill;
            host.Child = this;

            mParentForm = new GetRangeForm();
            mParentForm.Controls.Add(host);
            mParentForm.FormClosed += FormClosed;
        }

        void FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            ViewModel.IsEnabled = true;
        }

        public void Show(System.Windows.Forms.IWin32Window owner = null)
        {
            if (owner == null)
                mParentForm.Show();
            else
                mParentForm.Show(owner);
            
            ViewModel.IsEnabled = false;
        }

        private void DoneButton_Click(object sender, System.Windows.RoutedEventArgs e) {
        			
			ViewModel.SetSourceRange(Globals.Application.Range[RangeAddressTextBox.Text]);
            mParentForm.Close();
        }

        private void RangeAddressTextBox_TargetUpdated(object sender, System.Windows.Data.DataTransferEventArgs e)
        {
            mParentForm.Activate();
            ((Control)sender).Focus();
        }
    }
}
